package com.ruoyi.fsepc.service.impl;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.AMapUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LngLat;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.fsepc.domain.StFseLocation;
import com.ruoyi.fsepc.domain.StFseLocationLog;
import com.ruoyi.fsepc.mapper.StFseLocationLogMapper;
import com.ruoyi.fsepc.service.IStFseLocationLogService;
import com.ruoyi.system.api.domain.Configuration;
import com.ruoyi.system.api.domain.FseLocationLog;
import com.ruoyi.system.api.domain.User;
import com.ruoyi.system.api.mapper.ConfigurationMapper;
import com.ruoyi.system.api.mapper.UserMapper;
import com.ruoyi.web.controller.system.api.app.UserCcController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * FSE位置坐标日志Service业务层处理
 *
 * @author ruoyi
 * @date 2020-02-27
 */
@Service
public class StFseLocationLogServiceImpl implements IStFseLocationLogService {
    private static final Logger log = LoggerFactory.getLogger(StFseLocationLogServiceImpl.class);

    @Autowired
    private StFseLocationLogMapper stFseLocationLogMapper;

    @Autowired
    private ConfigurationMapper configurationMapper;


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private Global global;

    /**
     * 查询FSE位置坐标日志
     *
     * @param id FSE位置坐标日志ID
     * @return FSE位置坐标日志
     */
    @Override
    public StFseLocationLog selectStFseLocationLogById(Long id) {
        return stFseLocationLogMapper.selectStFseLocationLogById(id);
    }

    /**
     * 查询FSE位置坐标日志列表
     *
     * @param stFseLocationLog FSE位置坐标日志
     * @return FSE位置坐标日志
     */
    @Override
    public List<StFseLocationLog> selectStFseLocationLogList(StFseLocationLog stFseLocationLog) {
        return stFseLocationLogMapper.selectStFseLocationLogList(stFseLocationLog);
    }

    /**
     * 新增FSE位置坐标日志
     *
     * @param stFseLocationLog FSE位置坐标日志
     * @return 结果
     */
    @Override
    public int insertStFseLocationLog(StFseLocationLog stFseLocationLog) {
        //判断当前用户是否为休假状态
        User user = new User();
        user.setEnginnerId(Long.parseLong(stFseLocationLog.getFseId()));
        List<User> users = userMapper.selectUserList(user);
        boolean isWorkDay = false;
        if (users != null && users.size() > 0) {
            String workDay = "0";
            if (workDay.equals(users.get(0).getWorkday())) {
                isWorkDay = true;
            }
        }

        stFseLocationLog.setCreateTime(DateUtils.getNowDate());
        return stFseLocationLogMapper.insertStFseLocationLog(stFseLocationLog);

    }

    /**
     * 修改FSE位置坐标日志
     *
     * @param stFseLocationLog FSE位置坐标日志
     * @return 结果
     */
    @Override
    public int updateStFseLocationLog(StFseLocationLog stFseLocationLog) {
        stFseLocationLog.setUpdateTime(DateUtils.getNowDate());
        return stFseLocationLogMapper.updateStFseLocationLog(stFseLocationLog);
    }

    /**
     * 删除FSE位置坐标日志对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStFseLocationLogByIds(String ids) {
        return stFseLocationLogMapper.deleteStFseLocationLogByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除FSE位置坐标日志信息
     *
     * @param id FSE位置坐标日志ID
     * @return 结果
     */
    @Override
    public int deleteStFseLocationLogById(Long id) {
        return stFseLocationLogMapper.deleteStFseLocationLogById(id);
    }

    /**
     * @param stFseLocationLog
     * @return
     */
    @Override
    public List<StFseLocationLog> selectHistoryList(StFseLocationLog stFseLocationLog) {
        List<StFseLocationLog> list = stFseLocationLogMapper.selectHistoryList(stFseLocationLog);
        List<StFseLocationLog> result = new ArrayList();
        if (!ObjectUtils.isEmpty(list)) {
            result = dealWithFseLocationLog(list);
        }
        return result;
    }

    /**
     * 用于导出历史查询记录
     *
     * @param stFseLocationLog
     * @return
     */
    @Override
    public List<StFseLocationLog> newSelectHistoryList(StFseLocationLog stFseLocationLog) {
        return stFseLocationLogMapper.newSelectHistoryList(stFseLocationLog);
    }

    ;

    @Override
    public List<StFseLocationLog> dealWithFseLocationLog(List<StFseLocationLog> logList) {
        //去掉非工作日，时间数据
        List<StFseLocationLog> list = new ArrayList<StFseLocationLog>();
        if (null != logList && !logList.isEmpty()) {
            String beginTime = global.getWorkBeginTime();
            String endTimes = global.getWorkEndTime();
            for (StFseLocationLog fseLocation : logList) {
                try {
                    Date receiveDate = fseLocation.getReceiveDate();
                    if (ObjectUtils.isEmpty(receiveDate)) {
                        continue;
                    }
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String splitData = simpleDateFormat.format(receiveDate);
                    String[] agr = splitData.split(" ");
                    //判断该条数据日期是否是工作日
                    boolean isWeekend = DateUtils.isWeekend(agr[0]);
                    //判断该条数据的时间是否在指定范围内
                    boolean isEffectiveDate = DateUtils.isEffectiveDate(agr[1], beginTime, endTimes);

                    if (isWeekend && isEffectiveDate) {
                        list.add(fseLocation);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 配置参数，计算历史点的停留时间
        Double distance = 0D;
        Configuration configuration = new Configuration();
        configuration.setName("geographical_coordinates_distance");
        List<Configuration> configurations = configurationMapper.selectConfigurationList(configuration);
        if (configurations != null && configurations.size() > 0) {
            String val = configurations.get(0).getValue();
            if (com.ruoyi.common.utils.StringUtils.isNotEmpty(val)) {
                distance = Double.parseDouble(val);
            }
        }
        // 定位上报时间间隔
        Long timeLong = 0L;
        configuration.setName("location_reporting_interval");
        configurations = configurationMapper.selectConfigurationList(configuration);
        if (configurations != null && configurations.size() > 0) {
            String val = configurations.get(0).getValue();
            if (com.ruoyi.common.utils.StringUtils.isNotEmpty(val)) {
                timeLong = Long.parseLong(val);
            }
        }
        List<StFseLocationLog> result = new ArrayList<>();
        int lastResultIndex = 0; //最新存到result的对象所在list中的下标
        Long waste = 0L;
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                if (!DateUtils.isSameDay(list.get(i-1).getReceiveDate(), list.get(i ).getReceiveDate())) {
                    Date start = list.get(i-1).getReceiveDate();
                    Date end = list.get(i ).getReceiveDate();
                    waste = (end.getTime() - start.getTime()) / (1000 * 60) ;
                }
            }
        }
        for (int i = 0; i < list.size(); i++) {
            StFseLocationLog log = list.get(i);
            if (log.getPostx() != null && log.getPosty() != null) {
                if (result.size() == 0) {
                    // 首个标记时 直接存入结果
                    result.add(log);
                    // 更新坐在下标
                    lastResultIndex = i;
                } else if (StringUtils.isNotEmpty(log.getType()) && !log.getType().equals("1")) {
                    // 签到签离时 直接存入结果
                    result.add(log);
                } else {
                    // 距离计算
                    StFseLocationLog lastResult = list.get(lastResultIndex);
                    // 人员的实时经纬度
                    LngLat startAdd = new LngLat(log.getPostx(), log.getPosty());
                    // 获取仪器的经纬度
                    LngLat endAdd = new LngLat(lastResult.getPostx(), lastResult.getPosty());
                    // 计算获取两组经纬度的距离 取米
                    double meter1 = AMapUtils.calculateLineDistance(startAdd, endAdd);
                    // 更新上一点的停留时间
                    Date start = lastResult.getReceiveDate();
                    Date end = log.getReceiveDate();
                    long cha = 0; //时间差（分钟）
                    try {

                        cha = DateUtils.timeDiff(start, end);
                        if (!DateUtils.isSameDay(start, end)) {
                            cha -= waste;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (cha <= timeLong) {//5得是配置的变量
                        cha = 0;
                    } else {
                        cha = cha - timeLong;
                    }
                    lastResult.setLengthOfStay(cha);
                    if (meter1 > distance) { //超出参数设置的距离值
                        // 存入结果
                        result.add(log);
                        // 更新坐在下标（必须放最后）
                        lastResultIndex = i;
                    }
                }
            }
        }

        for (int i = 0; i < result.size(); i++) {
            if (StringUtils.isEmpty(result.get(i).getFseName())) {
                if (!StringUtils.isEmpty(result.get(i).getFseId())) {
                    List<User> userList = userMapper.getFseInformation(result.get(i).getFseId());
                    result.get(i).setFseName(userList.get(0).getName());
                }
            }
        }
        return result;
    }

}
